<?php
header("Content-Type: text/html; charset=UTF-8");
class Client {
	
	/**
	 * IP地址
	 */
	public static $ip = '127.0.0.1';
	/**
	 * 端口号
	 */
	public static $port = 80;
	public static $sendtime = 0;
	public static $filepath = 'client_log.log';
	public static $socket;
	public static $conn;
	public static $bstatus = false;
	/**
	 * 创建一个SOCKET
	 * 建立SOCKET的连接
	 */
	static function socket() {
		self::$socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP );
		if (self::$socket) {
			fputs ( fopen ( self::$filepath, 'a+' ), "start **r\n" . date ( "y-m-d,H:i:s", time () ) . " " . self::$socket . " socket_create成功 " );
		} else {
			fputs ( fopen ( self::$filepath, 'a+' ), date ( "y-m-d,H:i:s", time () ) . "socket_create失败 " );
		}
		self::$conn = socket_connect ( self::$socket, self::$ip, self::$port );
		self::$bstatus = self::$conn ? false : true;
		while ( self::$bstatus ) {
			self::$conn = socket_connect ( self::$socket, self::$ip, self::$port );
			self::$bstatus = self::$conn ? false : true;
		}
		if (self::$conn) {
			fputs ( fopen ( self::$filepath, 'a+' ), date ( "y-m-d,H:i:s", time () ) . "socket_connect成功 " );
		} else { /*
		        * 连接失败重启
		        */
			self::stop ();
			self::socket ();
		}
	}
	static function stop() {
		socket_close ( self::$socket );
		socket_close ( self::$conn );
	}
	/**
	 * 每隔1分钟发送链路检测
	 */
	static function sendCheck() {
		// 如果此时间无数据发送就发送'0000'
		while ( true ) {
			if ((time () - self::$sendtime) >= 60) {
				self::send ( '0000' );
			} else {
				set_time_limit ( 0 );
				sleep ( 1 );
			}
		}
	}
	static function send($data) {
		$msg = $data;
		if (! self::$socket)
			self::socket ();
		$write = socket_write ( self::$socket, $msg, strlen ( $msg ) );
		if ($write) {
			self::$sendtime = time ();
			echo 'socket_write成功:'.$msg;
			fputs ( fopen ( self::$filepath, 'a+' ), date ( "y-m-d,H:i:s", time () ) . "socket_write成功，数据为：" . $msg . "\n\r" );
		} else {
			echo 'socket_write失败';
			fputs ( fopen ( self::$filepath, 'a+' ), date ( "y-m-d,H:i:s", time () ) . "socket_write失败  \n\r" );
			self::stop ();
			self::socket ();
		}
	}
}
$client=new Client();
$client::socket ();
?>
